﻿using Matthew.DBManager;
using MvcApplicationTest.Models;
using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Routing;
using System.Collections;

namespace MvcApplicationTest.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            CacheUser user = new CacheUser();
            ViewBag.IsAuthenticated = user.IsAuthenticated;
            ViewBag.UserName = user.UserName;
            TempData["UserName"] = user.UserName;
            var allOrders = Utility.GetAllShopLists();
            Utility.GetSelectedExpectedOrderShops(user.UserName, DateTime.Now.ToString("yyyyMMdd"), allOrders);
            var model = new IndexModel() { AllOrders = allOrders };
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            return View(model);
        }

        public ActionResult About()
        {
            CacheUser user = new CacheUser();
            ViewBag.IsAuthenticated = user.IsAuthenticated;
            ViewBag.UserName = user.UserName;
            TempData["UserName"] = user.UserName;
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            CacheUser user = new CacheUser();
            ViewBag.IsAuthenticated = user.IsAuthenticated;
            ViewBag.UserName = user.UserName;
            ViewBag.IsAdmin = user.IsAdmin;
            TempData["UserName"] = user.UserName;
            ViewBag.Message = "Your contact page.";

            return View();
        }

        [HttpPost]
        public ActionResult WhichUWant(string str)
        {
            var selectedItems = Utility.GetSelectedListItems(str);
            var user = new CacheUser();
            string flagDay = DateTime.Now.ToString("yyyyMMdd");
            if (Utility.UpdateExpectedData(user.UserName, selectedItems, flagDay))
                return View();
            return RedirectToAction("ErrorPage", new { message = ErrorMessage.UpdateDataError });
        }

        [HttpPost]
        public ActionResult LeaveMessage(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                var user = new CacheUser();
                string htmlStr = Utility.DisPlayMessageOnBoard(str, user.DisplayName).ToString();
                return Json(htmlStr);
            }
            return Json(true);
        }

        [HttpPost]
        public ActionResult CheckRegister(string str)
        {
            return Json(Utility.CheckUserNameExist(str));
        }

        [HttpPost]
        public ActionResult HasBalance()
        {
            var user = new CacheUser();
            bool hasBalance = user.HasBalance;
            return Json(hasBalance);
        }

        [AllowAnonymous]
        public ActionResult OrderPage()
        {
            CacheUser user = new CacheUser();
            if (!user.CanOrder)
            {
                return RedirectToAction("ErrorPage", new { message = ErrorMessage.CannotOrder });
            }
            TempData["UserName"] = user.UserName;
            ViewBag.UserName = user.UserName;
            ViewBag.IsAuthenticated = user.IsAuthenticated;
            if (user.HasBalance)
            {
                ViewBag.Balance = DataBaseManager.GetUserInfo(user.UserName, false).UserBalance;
                ViewBag.Message = "Your OrderPage page.";
                ViewBag.OrderPicture = "";
                var orders = Utility.GetTodayOrderList(user.WhatToEat);
                UserOrderInfoModel model = new UserOrderInfoModel();
                model.Orders = orders;
                return View(model);
            }
            else
            {
                return RedirectToAction("ErrorPage", new { message = ErrorMessage.NotEnoughMoney });
            }
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult OrderPage(UserOrderInfoModel model)
        {
            if (model.HiddenValue == null)
                return RedirectToAction("ErrorPage", new { message = ErrorMessage.NotLogin });

            model.Orders = Utility.GetSelectedOrderItems(model.HiddenValue);
            if (model.Orders.Count > 0)
            {
                CacheUser user = new CacheUser();
                if (Utility.CheckUserOrder(model.Orders, user.WhatToEat))
                {
                    string userName = user.UserName;
                    DateTime now = DateTime.Now;
                    string orderTime = now.ToString("HH:mm:ss");
                    string flagDay = now.ToString("yyyyMMdd");
                    if (!string.IsNullOrEmpty(userName))
                    {
                        if (Utility.AddOrderForUser(userName, model.Orders, orderTime, flagDay))
                        {
                            TempData["FlagDay"] = flagDay;
                            ViewBag.Message = "Your OrderPage page.";
                            return RedirectToAction("OrderResult", "Home");
                        }
                    }
                    return RedirectToAction("ErrorPage", new { message = ErrorMessage.NotLogin });
                }
                return RedirectToAction("ErrorPage", new { message = ErrorMessage.UserAttackSystemError });
            }
            return RedirectToAction("ErrorPage", new { message = ErrorMessage.NotOrder });
        }



        [AllowAnonymous]
        //today's order
        public ActionResult OrderResult()
        {
            var user = new CacheUser();
            string userName = user.UserName;
            TempData["UserName"] = userName;
            ViewBag.UserName = userName;
            ViewBag.IsAuthenticated = user.IsAuthenticated;
            if (user.IsAuthenticated)
            {
                string flagDay = DateTime.Now.ToString("yyyyMMdd");
                ViewBag.UserOrderInfos = DataBaseManager.GetUserSpecialOrderInfos(userName, flagDay);
                ViewBag.UserBalance = DataBaseManager.GetUserInfo(userName, false).UserBalance;
                ViewBag.Message = "Your OrderResult page.";
                return View();
            }
            return RedirectToAction("ErrorPage", new { message = ErrorMessage.NotLogin });
        }

        [AllowAnonymous]
        public ActionResult OrderHistory()
        {
            var user = new CacheUser();
            string userName = user.UserName;
            TempData["UserName"] = userName;
            ViewBag.UserName = userName;
            ViewBag.IsAuthenticated = user.IsAuthenticated;
            if (user.IsAuthenticated)
            {
                ViewBag.UserOrderInfos = DataBaseManager.GetUserAllOrderInfos(userName);
                return View();
            }
            return RedirectToAction("ErrorPage", new { message = ErrorMessage.NotLogin });
        }

        [AllowAnonymous]
        public ActionResult DeleteOrders(string str)
        {
            var user = new CacheUser();
            if (user.IsAuthenticated)
            {
                var needToDeletedOrders = Utility.GetSelectedOrderItems(str);
                if (needToDeletedOrders.Count > 0)
                {
                    if (Utility.CheckUserOrder(needToDeletedOrders, user.WhatToEat))
                    {
                        string flagDay = DateTime.Now.ToString("yyyyMMdd");
                        Utility.DeleteOrderForUser(user.UserName, needToDeletedOrders, flagDay);
                        return Json(true);
                    }
                    return Json("UserAttackSystemError");
                }
                return Json(true);
            }
            return RedirectToAction("ErrorPage", new { message = ErrorMessage.NotLogin });
        }

        [AllowAnonymous]
        public ActionResult ChangeOrderOfToday(string str)
        {
            var user = new CacheUser();
            if (user.IsAuthenticated)
            {
                if (Utility.UpdateAdministratorInfo(true, Utility.ConvertToOrdersEnum(str)))
                {
                    return Json(true);
                }
            }
            return Json(false);
        }

        [AllowAnonymous]
        public ActionResult UserManager()
        {
            var user = new CacheUser();
            ViewBag.IsAuthenticated = user.IsAuthenticated;
            ViewBag.UserName = user.UserName;
            TempData["UserName"] = user.UserName;
            ViewBag.Title = "User Manager";
            if (user.IsAuthenticated)
            {
                ViewBag.Balance = DataBaseManager.GetUserInfo(user.UserName, false).UserBalance;
                return View();
            }
            return RedirectToAction("ErrorPage", new { message = ErrorMessage.NotLogin });
        }

        [AllowAnonymous]
        public ActionResult AdminManager()
        {
            var user = new CacheUser();
            string userName = user.UserName;
            TempData["UserName"] = userName;
            ViewBag.UserName = userName;
            ViewBag.IsAuthenticated = user.IsAuthenticated;
            ViewBag.IsChangeBalance = true;
            ViewBag.SearchName = userName;
            bool canOrder = user.CanOrder;
            ViewBag.CanOrder = canOrder.ToString();
            ViewBag.AllShops = Utility.GetAllShopLists();
            string flagDay = DateTime.Now.ToString("yyyyMMdd");
            var result = DataBaseManager.GetMostExpectedOrders(flagDay);
            ViewBag.ExpectedShops = result;
            ViewBag.WhatToEat = Utility.ConvertStringToDisplay(DataBaseManager.GetAdminManagerInfo().WhatToEat.ToString());
            if (result.Count > 0)
            {
                ViewBag.DropDownListValue = result[0].Shop;
            }
            else
            {
                ViewBag.DropDownListValue = ViewBag.WhatToEat;
            }
            if (canOrder)
            {
                ViewBag.CanOrderText = "Can Order Now.";
            }
            else
            {
                ViewBag.CanOrderText = "Can't Order Now.";
            }
            if (user.IsAuthenticated)
            {
                return View();
            }
            return RedirectToAction("ErrorPage", new { message = ErrorMessage.NotLogin });
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult AdminManager(ManageModel model)
        {
            var user = new CacheUser();
            string userName = user.UserName;
            TempData["UserName"] = userName;
            ViewBag.UserName = userName;
            ViewBag.IsAuthenticated = user.IsAuthenticated;
            ViewBag.IsChangeBalance = true;
            if (user.IsAuthenticated)
            {
                return View();
            }
            return RedirectToAction("ErrorPage", new { message = ErrorMessage.NotLogin });
        }

        [AllowAnonymous]
        public ActionResult ChangeUserBalance()
        {
            var user = new CacheUser();
            string userName = user.UserName;
            TempData["UserName"] = userName;
            ViewBag.UserName = userName;
            ViewBag.IsAuthenticated = user.IsAuthenticated;
            if (user.IsAuthenticated)
            {
                return View();
            }
            return RedirectToAction("ErrorPage", new { message = ErrorMessage.NotLogin });

        }

        [AllowAnonymous]
        public ActionResult ShowOrdersOfToday()
        {
            var user = new CacheUser();
            if (user.IsAuthenticated)
            {
                string userName = user.UserName;
                TempData["UserName"] = userName;
                ViewBag.UserName = userName;
                ViewBag.IsAuthenticated = user.IsAuthenticated;
                string flagDay = DateTime.Now.ToString("yyyyMMdd");
                //只能取到user,orders信息
                ViewBag.OrdersOfToday = Utility.GetAllOrdersByFlagDay(flagDay);
                int cost = 0;
                int count = 0;
                ViewBag.TotalOrders = Utility.GetTotalOrders(ViewBag.OrdersOfToday, ref cost, ref count);
                ViewBag.TotalCost = cost;
                ViewBag.TotalCount = count;
                return View();
            }
            return RedirectToAction("ErrorPage", new { message = ErrorMessage.NotLogin });
        }

        [AllowAnonymous]
        public ActionResult ShowAllUser()
        {
            var user = new CacheUser();
            if (user.IsAuthenticated)
            {
                string userName = user.UserName;
                TempData["UserName"] = userName;
                ViewBag.UserName = userName;
                ViewBag.IsAuthenticated = user.IsAuthenticated;
                ViewBag.AllUserInfo = Utility.GetAllUserInfo();
                return View();
            }
            return RedirectToAction("ErrorPage", new { message = ErrorMessage.NotLogin });
        }

        [AllowAnonymous]
        public ActionResult AdminManageSearchResult(string str)
        {
            //ViewBag.SearchName = str;
            string htmlStr = string.Empty;
            if ("Show All User".Equals(str))
            {
                htmlStr = Utility.SearchResultOfUser().ToString();
                return Json(htmlStr);
            }
            else if (string.IsNullOrEmpty(str) || str.Equals("Input Name"))
            {
                return Json(false);
            }
            htmlStr = Utility.SearchResultOfUser(str).ToString();
            return Json(htmlStr);
        }

        [AllowAnonymous]
        public ActionResult AdminManageBalanceChanged(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                try
                {
                    string[] infos = str.Split(',');
                    foreach (var info in infos)
                    {
                        string[] item = info.Split('|');
                        if (!Utility.ChangeUserBalance(item[0], item[1]))
                        {
                            return Json(false);
                        }
                    }
                    return Json(true);
                }
                catch
                {
                    return Json(false);
                }
            }
            return Json(false);
        }

        [AllowAnonymous]
        public ActionResult AdminManageCanOrderChange(string str)
        {
            string result = string.Empty;
            if (str.Equals("true"))
            {
                if (Utility.UpdateAdministratorInfo(true, Orders.Nothing))
                {

                    result = "true";
                    return Json(result);
                }
            }
            else if (str.Equals("false"))
            {
                if (Utility.UpdateAdministratorInfo(false, Orders.Nothing))
                {
                    result = "false";
                    return Json(result);
                }
            }
            return RedirectToAction("ErrorPage", new { message = ErrorMessage.UpdateDataError });
        }

        [AllowAnonymous]
        public ActionResult ErrorPage(ErrorMessage? message)
        {
            var user = new CacheUser();
            ViewBag.IsAuthenticated = user.IsAuthenticated;
            ViewBag.UserName = user.UserName;
            TempData["UserName"] = user.UserName;
            if (user.IsAuthenticated)
            {
                switch (message)
                {
                    case ErrorMessage.NotEnoughMoney:
                        ViewBag.Title = "Sorry, your money is not enough.";
                        break;
                    case ErrorMessage.NotLogin:
                        ViewBag.Title = "Please login first.";
                        break;
                    case ErrorMessage.NotOrder:
                        ViewBag.Title = "Please order first.";
                        break;
                    case ErrorMessage.UpdateDataError:
                        ViewBag.Title = "Error occurred while update data";
                        break;
                    case ErrorMessage.ModifySucceed:
                        ViewBag.Title = "Modify succeed.";
                        break;
                    case ErrorMessage.CannotOrder:
                        ViewBag.Title = "It's not the time to order, please contact the admin.";
                        break;
                    case ErrorMessage.UserAttackSystemError:
                        ViewBag.Title = "Warning, if u try to attack the system second time, your user will be record in database and the user would be killed.";
                        break;
                    default:
                        ViewBag.Title = "Hehe.";
                        break;
                }
            }
            else
            {
                ViewBag.Title = "Please login first.";
            }

            return View();
        }

        [AllowAnonymous]
        public ActionResult ShopPage(string id)
        {
            var user = new CacheUser();
            if (user.IsAuthenticated)
            {
                ViewBag.IsAuthenticated = user.IsAuthenticated;
                ViewBag.UserName = user.UserName;
                TempData["UserName"] = user.UserName;
                string displayShop = Utility.ConvertStringToDisplay(id);
                if (displayShop != null)
                {
                    ViewBag.Shop = displayShop;
                    return View();
                }
                else
                {
                    return RedirectToAction("ErrorPage", new { message = ErrorMessage.UpdateDataError });
                }
            }
            else
            {
                return RedirectToAction("ErrorPage", new { message = ErrorMessage.NotLogin });
            }
        }
    }

    public enum ErrorMessage
    {
        NotEnoughMoney,
        NotLogin,
        UpdateDataError,
        NotOrder,
        ChangeUserBalanceError,
        ModifySucceed,
        CannotOrder,
        UserAttackSystemError,

    }
}
